import { Service } from 'egg';

/**
 * Article Service
 */
export default class Article extends Service {

  /**
   * 最新的文章列表
   * @param offset -偏移量
   * @param limit -页限制
   */
  public async getArticlelist(offset: number, limit: number) {
    // console.log(offset, limit);
    const { app } = this;
    const articleList = await app.mysql.select('article_users', {
      orders: [[ 'createAt', 'desc' ]],
      // columns: [ 'aid', 'uid', 'title', 'createAt' ],
      limit,
      offset,
    });
    const allCount = await this.getAll().then(res => {
      return res;
    });
    const allPage = Math.ceil(allCount / limit);
    return {
      articleList,
      allCount,
      allPage,
    };
  }


  /**
   * 全部列表
   */
  public async getAll() {
    const { app } = this;
    const allList = await app.mysql.select('articles', {});
    return allList.length;
  }


  /**
   * create a new article
   * @param uid -用户id
   * @param title -标题
   * @param content -内容
   */
  public async createArticle(uid: number, title: string, content: string, tid: number) {
    const { app } = this;
    const createAt = new Date().valueOf();
    const article = {
      uid,
      title,
      tid,
      content,
      createAt,
    };
    const createResult = await app.mysql.insert('articles', article);
    return createResult;
  }

  /**
  * 文章详情
  * @param aid -文章id
  */
  public async getArticleDetail(aid: number) {
    const { app } = this;
    const detail = app.mysql.select('article_detail', {
      where: {
        aid,
      },
    });
    return detail;
  }

  /**
   * 根据分类获取列表
   */
  public async getAllByTag(tid: number) {
    const { app } = this;
    const allListByTag = await app.mysql.select('articles', {
      where: {
        tid,
      },
    });
    return allListByTag.length;
  }

  /**
   * 根据分类获取列表
   * @param tid -分类
   * @param offset -偏移量
   * @param limit -页限制
   */
  public async getArticleByTag(tid: number, offset = 0, limit = 10) {
    const { app } = this;
    const listByTag = await app.mysql.select('article_users', {
      where: {
        tid,
      },
      orders: [[ 'createAt', 'desc' ]],
      limit,
      offset,
    });
    const allCount = await this.getAllByTag(tid).then(res => {
      return res;
    });
    const allPage = Math.ceil(allCount / limit);
    return {
      listByTag,
      allCount,
      allPage,
    };
  }

  /**
   * 根据文章ID删除文章
   * @param aid -文章ID
   */
  public async deleteArticleById(aid: number) {
    const { app } = this;
    const result = await app.mysql.delete('articles', {
      aid,
    });
    if (result.affectedRows === 1) {
      return result;
    }
  }
}
